package com.etoak.service.impl;

import cn.hutool.core.date.DateUtil;
import com.etoak.common.core.exception.CustomException;
import com.etoak.common.core.vo.PageVo;
import com.etoak.entity.Dishes;
import com.etoak.mapper.DishesMapper;
import com.etoak.service.DishesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etoak.vo.DishesVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author etoak
 * @since 2025-08-25
 */
@Service
public class DishesServiceImpl extends ServiceImpl<DishesMapper, Dishes> implements DishesService {

    /**
     * 添加菜品
     *
     * @param dishes
     */
    @Override
    public void add(Dishes dishes) {
        if (ObjectUtils.isNotEmpty(getByName(dishes.getName()))) {
            throw new CustomException("菜品名称重复");
        }
        dishes.setCreateTime(DateUtil.now());
        this.save(dishes);
    }

    /**
     * 通过名字得到菜品
     *
     * @param dishesName
     * @return
     */
    @Override
    public Dishes getByName(String dishesName) {
        return lambdaQuery().eq(Dishes::getName, dishesName).one();
    }

    /**
     * 分页查询、条件查询
     *
     * @param pageNum
     * @param pageSize
     * @param dishes
     * @return
     */
    @Override
    public PageVo<DishesVO> getList(int pageNum, int pageSize, Dishes dishes) {
        PageHelper.startPage(pageNum, pageSize);
        List<DishesVO> dishesVOList = baseMapper.getList(dishes);
        PageInfo<DishesVO> pageInfo = new PageInfo<>(dishesVOList);
        return new PageVo<>(pageInfo.getTotal(), dishesVOList);
    }

    @Override
    public void updateDishes(int id, Dishes dishes) {
        if(ObjectUtils.isEmpty(getById(id))) {
            throw new CustomException("菜品不存在");
        }

        String dishesName = dishes.getName();
        if (StringUtils.isNotBlank(dishesName)){
            Dishes saveDishes = this.getByName(dishesName);
            if (ObjectUtils.isNotEmpty(saveDishes) && !saveDishes.getId().equals(id)) {
                throw new CustomException("不能将名称修改为其他菜品的名字！");
            }
        }

        dishes.setId(id);
        dishes.setUpdateTime(DateUtil.now());
        this.updateById(dishes);
    }

    @Override
    public void delete(int id) {
        if(ObjectUtils.isEmpty(getById(id))) {
            throw new CustomException("菜品不存在");
        }
        removeById(id);
    }
}
